﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using XuLyDuLieu.ClassDetails;

namespace XuLyDuLieu
{
    public partial class frmMain : Form
    {
        #region "[Khai báo biến toan cục]"
        public XuLyDuLieu.Core.DataProcessing xuly = new XuLyDuLieu.Core.Example_2();

        //lấy danh sách các thông tin từ file text
        List<string> listContent = new List<string>();

        //lấy danh sách các tiêu đề.
        List<string> listTitle = new List<string>();


         //lấy danh sách các cột
        List<Cot> laydanhsachcaccot = new List<Cot>();
        /// <summary>
        /// kiểu chia giỏ
        /// </summary>
        public static Core.DataProcessing.KieuChia KieuChia = Core.DataProcessing.KieuChia.NULL;

        /// <summary>
        /// kiểu chuẩn hóa
        /// </summary>
        public static Core.DataProcessing.KieuChuanHoa KieuChuanHoa = Core.DataProcessing.KieuChuanHoa.NULL;
        /// <summary>
        /// số lượng giỏ cần chia
        /// </summary>
        public static int SoLuongGio = 0;

        /// <summary>
        /// mã cột cần chia giỏ
        /// </summary>
        public static int m_maCotCanChia = 1;

        /// <summary>
        /// thông tin nhòm giỏ được chia theo chiều rộng.
        /// </summary>
        public static NhomGio m_nhomGioDuocChia = null;

        /// <summary>
        /// trạng thái nhóm hàm nào đang được sử dụng
        /// <para>Có thể là nhóm hàm chia giỏ: 100</para>
        /// <para>Có thể là nhóm hàm chuẩn hóa: 200</para>
        /// </summary>
        public static int m_TrangThai = 0;

        /// <summary>
        /// chuẫn hóa dữ liệu
        /// <para>Khi người dùng chọn Chuẩn hóa dữ liệu 1 trong 2 kiểu:</para>
        /// <para>Min-Max</para>
        /// <para>Z-Score</para>
        /// </summary>
        public List<ChuanHoaDuLieu> m_ChuanHoaDuLieu = new List<ChuanHoaDuLieu>();

        /// <summary>
        /// giá trị lớn nhất
        /// <para>chỉ có được sử dụng nếu người dùng chọn chuẩn</para>
        /// <para>hóa Min-Max</para>
        /// </summary>
        public static double m_GiaTriLonNhat = 0;

        /// <summary>
        /// giá trị nhỏ nhất
        /// <para>chỉ có được sử dụng nếu người dùng chọn chuẩn</para>
        /// <para>hóa Min-Max</para>
        /// </summary>
        public static double m_GiaTriNhoNhat = 0;
        #endregion

        #region "[khởi tạo mặc định]"
        public frmMain()
        {
            InitializeComponent();
        }
        #endregion

        #region "[xử lý cho chức năng mở file]"
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                //open file...
                OpenFileDialog open = new OpenFileDialog();
                open.Filter = "|*.csv";
                DialogResult result = open.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    Program.m_Path = open.FileName;
                    
                }

                //hiển thi danh sach các thuoc tinh
                ShowListAttributes();
            }
            catch { }
        }
        #endregion

        #region "[hiển thị danh sách các thuộc tính]"
        /// <summary>
        /// hiển thị danh sách các thuộc tính
        /// </summary>
        private void ShowListAttributes()
        {
            try {
                ////doc file. và trả ra danh sách các thuộc tính
               listContent = xuly.DocFileCSV(Program.m_Path);

                //lấy danh sách các tiêu đề.
                listTitle = xuly.DanhSachThuocTinh(listContent[0]);

                List<ItemAttribute> listShows = new List<ItemAttribute>();
                //hiển thị danh sách các tiêu đề lên datagridview;
                for (int i = 0; i < listTitle.Count; i++)
                {
                    ItemAttribute Item = new ItemAttribute();
                    Item.Check = false;
                    Item.STT = i + 1;
                    Item.Name = listTitle[i].Replace("'", "");
                    listShows.Add(Item);
                }
                LoadDataGridViewAttribute(listShows);

                ShowCurrentRelation();

                //lấy danh sách các cột
                 laydanhsachcaccot = xuly.LayDanhSachCacCot(listContent);
            }
            catch {
                MessageBox.Show("File không có dữ liệu\r\nHoặc đang được mở bởi một ứng dụng khác", "Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
        }
        #endregion

        #region "[hiển thị thông tin trên "Dữ Liệu"]"
        /// <summary>
        /// hiển thị thông tin trên "Dữ Liệu"
        /// </summary>
        /// <param name="listContent">danh sách các đối tượng</param>
        private void ShowCurrentRelation()
        {
            try { 
                //lấy tên dữ liệu
                lbTenDuLieu.Text = Program.m_Path.Split('\\').Last().Split('.').First();

                //lấy số mẫu.
                lbSoMau.Text = (listContent.Count - 1).ToString();//-1 là bỏ đi dòng tiêu đề

                //lấy số thuộc tính
                lbSoThuocTinh.Text = (listContent[0].Split(',').ToList()).Count.ToString();
            }
            catch { }
        }
        #endregion

        #region "[hiển thị danh sách các thuộc tính]"
        /// <summary>
        /// hiển thị danh sách các thuộc tính
        /// </summary>
        /// <param name="listShows"></param>
        private void LoadDataGridViewAttribute(List<ItemAttribute> listShows)
        {
            try {
                dgvThuocTinh.DataSource = listShows;
                dgvThuocTinh.Refresh();
            }
            catch { }
        }
        #endregion

        #region "[Hiển thị thuộc tính Numeric khi chưa chia giỏ]"
        /// <summary>
        /// Hiển thị thuộc tính Numeric khi chưa chia giỏ
        /// </summary>
        /// <param name="_dgvInput"></param>
        /// <param name="cotSelected"></param>
        public void HienThiThuocTinhKieuNominalKhiChuaChiaGio(DataGridView _dgvInput, Cot cotSelected)
        {
            try {
                //tạo gridview có 3 cột.
                dgvThongTinThuocTinh.Columns.Clear();
                dgvThongTinThuocTinh.ColumnCount = 3;
                dgvThongTinThuocTinh.ColumnHeadersVisible = true;

                // Set the column header style.
                DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

                columnHeaderStyle.BackColor = Color.Beige;
                columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
                dgvThongTinThuocTinh.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

                // Set the column header names.
                dgvThongTinThuocTinh.Columns[0].Name = "colNo";
                dgvThongTinThuocTinh.Columns[0].HeaderText = "No.";

                dgvThongTinThuocTinh.Columns[1].Name = "colLable";
                dgvThongTinThuocTinh.Columns[1].HeaderText = "Nhãn";

                dgvThongTinThuocTinh.Columns[2].Name = "colCount";
                dgvThongTinThuocTinh.Columns[2].HeaderText = "Số Lượng";


                //thêm dữ liệu 
                //tìm tần số xuất hiện
                List<XuatHien> tanSoXuatHien = xuly.TimTanSoXuatHienCuaDoiTuong(cotSelected.PhanTu);

                for (int i = 0; i < tanSoXuatHien.Count; i++)
                {
                    string[] hienThi = new string[] { (i + 1).ToString(), tanSoXuatHien[i].TenThuocTinh.Replace(@"\","").Replace("\'",""), tanSoXuatHien[i].SoLanXuatHien.ToString() };
                    dgvThongTinThuocTinh.Rows.Add(hienThi);
                }
            }
            catch { }
        }
        #endregion

        #region "[Hiển thị thuộc tính bình thường khi chưa thực hiện chia giỏ]"
        /// <summary>
        /// Hiển thị thuộc tính bình thường khi chưa thực hiện chia giỏ
        /// </summary>
        /// <param name="_dgvInput"></param>
        public void HienThiThuocKieuNumericKhiChuaChiaGio(DataGridView _dgvInput, Cot cotSelected)
        {
            try {
                //nếu không chia giỏ thì chia làm 2 cột
                _dgvInput.Columns.Clear();
                _dgvInput.ColumnCount = 2;
                _dgvInput.ColumnHeadersVisible = true;

                // Set the column header style.
                DataGridViewCellStyle columnHeaderStyle1 = new DataGridViewCellStyle();

                columnHeaderStyle1.BackColor = Color.Beige;
                columnHeaderStyle1.Font = new Font("Verdana", 10, FontStyle.Bold);
                _dgvInput.ColumnHeadersDefaultCellStyle = columnHeaderStyle1;

                // Set the column header names.
                _dgvInput.Columns[0].Name = "colThongKe";
                _dgvInput.Columns[0].HeaderText = "Thống kê";

                _dgvInput.Columns[1].Name = "colGiaTri";
                _dgvInput.Columns[1].HeaderText = "Giá Trị";

                ThongKeTrenCotNumeric thongKe = xuly.ThongKeCacThuocTinhTrenCot(cotSelected);
                string[] arr1 = new string[] { "Giá trị nhỏ nhất", thongKe.Min.ToString() };
                string[] arr2 = new string[] { "Giá trị lớn nhất", thongKe.Max.ToString() };
                string[] arr3 = new string[] { "Giá trị trung bình", Math.Round(thongKe.Mean, 3).ToString() };
                string[] arr4 = new string[] { "Độ lệch chuẩn", Math.Round(thongKe.StdDev, 3).ToString() };

                _dgvInput.Rows.Add(arr1);
                _dgvInput.Rows.Add(arr2);
                _dgvInput.Rows.Add(arr3);
                _dgvInput.Rows.Add(arr4);
            }
            catch { }
        }
        #endregion

        #region "[Chia giỏ thuộc tính theo chiều rộng]"
        /// <summary>
        /// Chia giỏ thuộc tính theo chiều rộng
        /// </summary>
        /// <param name="_dgv"></param>
        public void ChiaCotTheoChieuRong(DataGridView _dgv)
        {
            try {
                //hiển thị cột chia theo chiều rộng.
                _dgv.Columns.Clear();
                _dgv.ColumnCount = 3;
                _dgv.ColumnHeadersVisible = true;

                // Set the column header style.
                DataGridViewCellStyle columnHeaderStyle2 = new DataGridViewCellStyle();

                columnHeaderStyle2.BackColor = Color.Beige;
                columnHeaderStyle2.Font = new Font("Verdana", 10, FontStyle.Bold);
                dgvThongTinThuocTinh.ColumnHeadersDefaultCellStyle = columnHeaderStyle2;

                // Set the column header names.
                _dgv.Columns[0].Name = "colNo";
                _dgv.Columns[0].HeaderText = "STT";

                _dgv.Columns[1].Name = "colLable";
                _dgv.Columns[1].HeaderText = "Nhãn";

                _dgv.Columns[2].Name = "colCount";
                _dgv.Columns[2].HeaderText = "Số Lượng";

                for (int i = 0; i < m_nhomGioDuocChia.GioThuocTinhs.Count; i++)
                {
                    Gio gioSelected = m_nhomGioDuocChia.GioThuocTinhs[i];
                    string[] newRow = new string[] { (i + 1).ToString() ,"[" + gioSelected.GioiHanDuoi.ToString()
                        + "-" + gioSelected.GioiHanTren.ToString() + ")",gioSelected.SoLuong.ToString()};

                    ///hiển thị trên lưới
                    _dgv.Rows.Add(newRow);
                }
               
            }
            catch { }
        }
        #endregion

        #region "[hiển thị thông tin thuộc tính đang được chọn]"
        /// <summary>
        /// hiển thị thông tin thuộc tính đang được chọn
        /// </summary>
        /// <param name="objectSelected">đối tượng thuộc tính đang đucợ chọn</param>
        private void ShowSelectedAttribute(ItemAttribute objectSelected)
        {
            try {
                
                Cot cotSelected = laydanhsachcaccot[objectSelected.STT - 1];

                int soLuongCot = cotSelected.PhanTu.Count;

                ///lấy tên thuôc tính đang được chọn
                lbTenThuocTinh.Text = objectSelected.Name;

                ///hiển thị kiểu dữ liệu
                lbKieuDuLieu.Text = cotSelected.KieuDuLieu.ToString();

                //số mẫu thiếu gía trị
               int soMauThieuGiaTri = xuly.DemSoLuongGiaTriBiThieuTrongMotCot(cotSelected);
               double phanTramSMTGT = Math.Round(((1.0 * soMauThieuGiaTri / (soLuongCot)) * 100.0), 2);
               lbSoMauThieuGiaTri.Text = soMauThieuGiaTri.ToString() + " (" + phanTramSMTGT.ToString() + "%)";

                //số giá trị khác nhau
                lnSoGiaTriPhanBiet.Text = xuly.DemSoGiaTriKhacNhauTrongMotCot(cotSelected).ToString();

                //số mẫu khác biệt.
                int soMauKhacBiet = xuly.DemSoMauKhongCoGiaTriTrungVoiMauKhac(cotSelected);
                double phanTramSMKB = Math.Round(((1.0 * soMauKhacBiet / (soLuongCot)) * 100.0), 2);
                lbSoMauKhacBiet.Text = soMauKhacBiet.ToString() + " (" + phanTramSMKB.ToString() + "%)";

               //hiển thị thông số chi tiết.
                //kiểm tra kiểu dữ liệu
                switch (laydanhsachcaccot[objectSelected.STT - 1].KieuDuLieu)
                { 
                    case Core.DataProcessing.KieuDuLieu.Nominal:
                        HienThiThuocTinhKieuNominalKhiChuaChiaGio(dgvThongTinThuocTinh, cotSelected);
                        break;
                    case Core.DataProcessing.KieuDuLieu.Numeric:
                        //kiểm tra có chia giỏ chưa.

                        #region "[Chia giỏ dữ liệu]"
                        switch (KieuChia)
                        { 
                            case Core.DataProcessing.KieuChia.NULL:
                                HienThiThuocKieuNumericKhiChuaChiaGio(dgvThongTinThuocTinh, cotSelected);
                                break;
                            //nếu có chia giỏ thì chia làm 3 cột.
                            case Core.DataProcessing.KieuChia.TheoChieuRong:
                                #region "[xử lý theo chiều rộng]"
                                if (objectSelected.STT == m_maCotCanChia && m_maCotCanChia > 0)
                                {
                                    ChiaCotTheoChieuRong(dgvThongTinThuocTinh);
                                }
                                else
                                {
                                    //chia theo kieu bình thuong.
                                    HienThiThuocKieuNumericKhiChuaChiaGio(dgvThongTinThuocTinh, cotSelected);
                                }
                                #endregion
                                break;
                            case Core.DataProcessing.KieuChia.TheoChieuSau:

                                #region "[Xử lý theo chiều sâu]"
                                if (objectSelected.STT == m_maCotCanChia && m_maCotCanChia > 0)
                                {
                                    ChiaCotTheoChieuSau(dgvThongTinThuocTinh);
                                }
                                else
                                {
                                    //chia theo kieu bình thuong.
                                    HienThiThuocKieuNumericKhiChuaChiaGio(dgvThongTinThuocTinh, cotSelected);
                                }
                                #endregion
                                break;
                        }
                        #endregion

                        #region "[Chuẩn hóa dữ liệu]"
                        if (KieuChuanHoa != Core.DataProcessing.KieuChuanHoa.NULL)
                        {
                            HienThiThuocTinhKieuNumericChuanHoaDuLieu(dgvThongTinThuocTinh, m_ChuanHoaDuLieu[objectSelected.STT-1]);
                        }
                        #endregion
                        break;
                }
                dgvThongTinThuocTinh.Refresh();
            }
            catch { }
        }

        private void HienThiThuocTinhKieuNumericChuanHoaDuLieu(DataGridView _dgvInput, ChuanHoaDuLieu _ChuanHoaDuLieu)
        {
            try
            {
                //nếu không chia giỏ thì chia làm 2 cột
                _dgvInput.Columns.Clear();
                _dgvInput.ColumnCount = 2;
                _dgvInput.ColumnHeadersVisible = true;

                // Set the column header style.
                DataGridViewCellStyle columnHeaderStyle1 = new DataGridViewCellStyle();

                columnHeaderStyle1.BackColor = Color.Beige;
                columnHeaderStyle1.Font = new Font("Verdana", 10, FontStyle.Bold);
                _dgvInput.ColumnHeadersDefaultCellStyle = columnHeaderStyle1;

                // Set the column header names.
                _dgvInput.Columns[0].Name = "colThongKe";
                _dgvInput.Columns[0].HeaderText = "Thống kê";

                _dgvInput.Columns[1].Name = "colGiaTri";
                _dgvInput.Columns[1].HeaderText = "Giá Trị";

              
                string[] arr1 = new string[] { "Giá trị nhỏ nhất", _ChuanHoaDuLieu.Min.ToString() };
                string[] arr2 = new string[] { "Giá trị lớn nhất", _ChuanHoaDuLieu.Max.ToString() };
                string[] arr3 = new string[] { "Giá trị trung bình", Math.Round(_ChuanHoaDuLieu.Mean, 3).ToString() };
                string[] arr4 = new string[] { "Độ lệch chuẩn", Math.Round(_ChuanHoaDuLieu.StdDev, 3).ToString() };
                //object[] arr = new object[] { arr1, arr2, arr3, arr4 };

                _dgvInput.Rows.Add(arr1);
                _dgvInput.Rows.Add(arr2);
                _dgvInput.Rows.Add(arr3);
                _dgvInput.Rows.Add(arr4);
            }
            catch { }
        }
        #endregion

        #region "[Chia cột theo chiều sâu]"
        /// <summary>
        /// Chia cột theo chiều sâu
        /// </summary>
        /// <param name="dgvThongTinThuocTinh"></param>
        private void ChiaCotTheoChieuSau(DataGridView _dgv)
        {
            try{
             //hiển thị cột chia theo chiều rộng.
                _dgv.Columns.Clear();
                _dgv.ColumnCount = 3;
                _dgv.ColumnHeadersVisible = true;

                // Set the column header style.
                DataGridViewCellStyle columnHeaderStyle2 = new DataGridViewCellStyle();

                columnHeaderStyle2.BackColor = Color.Beige;
                columnHeaderStyle2.Font = new Font("Verdana", 10, FontStyle.Bold);
                dgvThongTinThuocTinh.ColumnHeadersDefaultCellStyle = columnHeaderStyle2;

                // Set the column header names.
                _dgv.Columns[0].Name = "colNo";
                _dgv.Columns[0].HeaderText = "STT";

                _dgv.Columns[1].Name = "colLable";
                _dgv.Columns[1].HeaderText = "Nhãn";

                _dgv.Columns[2].Name = "colCount";
                _dgv.Columns[2].HeaderText = "Số Lượng";

                for (int i = 0; i < m_nhomGioDuocChia.GioThuocTinhs.Count; i++)
                {
                    Gio gioSelected = m_nhomGioDuocChia.GioThuocTinhs[i];
                    string[] newRow = new string[] { (i + 1).ToString() ,"[" + gioSelected.GioiHanDuoi.ToString()
                        + "-" + gioSelected.GioiHanTren.ToString() + "]",gioSelected.SoLuong.ToString()};

                    ///hiển thị trên lưới
                    _dgv.Rows.Add(newRow);
                }
               
            }
            catch { }
        }
        #endregion

        #region "[chọn 1 dòng trên lưới bên trái]"
        private void dgvThuocTinh_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //lấy đối tượng đang được chọn
                ItemAttribute objectSelected = (ItemAttribute)dgvThuocTinh.CurrentRow.DataBoundItem;
                ShowSelectedAttribute(objectSelected);
               
            }
            catch { }
        }
        #endregion

        #region "[Chức năng chọn bộ lộc]"
        private void btnChonBoLoc_Click(object sender, EventArgs e)
        {
            try
            {
                frmBoLoc frm = new frmBoLoc();
                frm.ShowDialog();
                string noiDungTextBox = string.Empty;
                //if (KieuChia == Core.DataProcessing.KieuChia.TheoChieuRong)
                //{
                //    // chia thuộc tính theo chiều rộng
                //    noiDungTextBox = "Chia giỏ theo chiều rộng - click chuột để cấu hình";
                //}
                //else
                //{
                //    if (KieuChia == Core.DataProcessing.KieuChia.TheoChieuSau)
                //    {
                //        //chia thuộc tính theo chiều sâu

                //        noiDungTextBox = "Chia giỏ theo chiều sâu - click chuột để cấu hình";
                //    }
                //}
                if (m_TrangThai == 100)
                { 
                    //nhóm hàm chia giỏ thuộc tính
                    noiDungTextBox = "Chia giỏ thuộc tính - click để chọn cấu hình";
                }
                if (m_TrangThai == 200)
                { 
                    //nhóm hàm chuẩn hóa thuộc tính
                    noiDungTextBox = "Chuẩn hóa thuộc tính - click để chọn cấu hình";
                }
                textBox1.Text = noiDungTextBox;
            }
            catch { }
        }
        #endregion

        #region "[chức năng khi click vào textbox]"
        private void textBox1_Click(object sender, EventArgs e)
        {
            try
            {
                //click de chon thuoc tinh
                if (m_TrangThai==100)//KieuChia != Core.DataProcessing.KieuChia.NULL)
                {
                    frmCauHinhBoLoc frm = new frmCauHinhBoLoc();
                    frm.ShowDialog();

                }
                else {
                    if (m_TrangThai==200)//KieuChuanHoa != Core.DataProcessing.KieuChuanHoa.NULL)
                    {
                        frmKieuChuanHoa frm = new frmKieuChuanHoa();
                        frm.ShowDialog();
                    }
                }
            }
            catch { }
        }
        #endregion

        #region "[áp dụng bộ lọc]"
        private void btnApDungBoLoc_Click(object sender, EventArgs e)
        {
            try {
                if (SoLuongGio > 0)
                { 
                    //chia giỏ thuộc tính

                    if (m_TrangThai==100)
                    {
                        if (m_maCotCanChia < laydanhsachcaccot.Count)
                        {
                            //lấy giỏ của cột cần chia.
                            m_nhomGioDuocChia = xuly.ChiaGioThuocTinh(laydanhsachcaccot, SoLuongGio, KieuChia)[m_maCotCanChia - 1];
                        }
                        else {
                            m_maCotCanChia = 0;
                        }
                    }
                }
                if (m_TrangThai == 200)
                {
                    m_ChuanHoaDuLieu = xuly.ChuanHoaThuocTinhCoKieuNumberic(laydanhsachcaccot, m_GiaTriNhoNhat, m_GiaTriLonNhat, KieuChuanHoa);
                }
                dgvThuocTinh.Refresh();
                dgvThongTinThuocTinh.Refresh();
            }
           catch { }
        }
        #endregion

        #region "[Function Save file ARFF]"
        public List<string> SaveFileARFF(string fileName)
        {
            List<string> noiDung = new List<string>();
            try
            {                                   
                //Relation tên file trong file ARFF
                string _relation = "@relation '" + fileName + "'";
                noiDung.Add(_relation);
                noiDung.Add(System.Environment.NewLine);

                //Thêm các cột attribute
                for (int i = 0; i < listTitle.Count; i++)
                {
                    string _title = listTitle[i].Replace('"', ' ').Trim();

                    string _titleAttr = string.Format("@attribute '{0}' {1}",_title , laydanhsachcaccot[i].KieuDuLieu.ToString());
                    //string _titileAttr =  "@attribute" + " '" + listTitle[i].ToString() + "' " + laydanhsachcaccot[i].KieuDuLieu.ToString();
                    noiDung.Add(_titleAttr);
                }
                noiDung.Add(System.Environment.NewLine);
                //Bắt đầu insert nội dung
                noiDung.Add("@data");

                List<object> listResult = new List<object>();
                //chuyển từ cột sang dòng
                for (int i = 0; i < laydanhsachcaccot[0].PhanTu.Count; i++)
                {
                    List<string> listContent = new List<string>();
                    for (int j = 0; j < laydanhsachcaccot.Count; j++)
                    {
                        listContent.Add(laydanhsachcaccot[j].PhanTu[i].TenDoiTuong);
                    }
                    listResult.Add(listContent);
                }

                foreach (List<string> ItemArr in listResult)
                {
                    string strTemp = string.Empty;
                    for (int irun = 0; irun < ItemArr.Count; irun++)
                    {
                        if (irun == 0)
                            strTemp += ItemArr[irun];
                        else
                            strTemp += "," + ItemArr[irun];
                    }
                    noiDung.Add(strTemp);
                }
                
            }
            catch { }
            return noiDung;

        }
        #endregion

        #region "[Nut save]"
        private void btnSave_Click(object sender, EventArgs e)
        {

            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.FileName = Program.m_Path;
                saveFile.Filter = "Arff data files (*.arff)|*.arff";

                List<string> strNoiDung = SaveFileARFF(System.IO.Path.GetFileNameWithoutExtension(saveFile.FileName));

                DialogResult result = saveFile.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string str = saveFile.FileName;

                    bool isSuccess = xuly.GhiFile(strNoiDung, str);
                    if (isSuccess)
                    {
                        MessageBox.Show("Ghi file thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                }
            }
            catch { }
        }
        
        private void GhiFileCSV(List<string> strNoiDung)
        {
            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.FileName = Program.m_Path;
                saveFile.Filter = "csv files (*.csv)|*.csv|Arff data files (*.arff)|*.arff";

                DialogResult result = saveFile.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string str = saveFile.FileName;



                    bool isSuccess = xuly.GhiFile(strNoiDung, str);
                    if (isSuccess)
                    {
                        MessageBox.Show("Ghi file thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                }
            }
            catch { }
        }
        #endregion

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            { 
                if (listTitle.Count > 0)
                {
                    //điền dữ liệu còn thiếu.
                    laydanhsachcaccot = xuly.DienGiaTriBiThieu(laydanhsachcaccot);

                    //chuẫn hóa ra thành nội dung.
                    string title = string.Empty;
                    for (int i = 0; i < listTitle.Count;i++ )
                    {
                        if (i == 0)
                            title += listTitle[i];
                        else
                            title += "," + listTitle[i];
                    }

                    title.Replace("'", "");

                    List<object> listResult = new List<object>();
                     //chuyển từ cột sang dòng
                    for (int i = 0; i < laydanhsachcaccot[0].PhanTu.Count;i++ )
                    {
                        List<string> listContent = new List<string>();
                        for (int j = 0; j < laydanhsachcaccot.Count; j++)
                        {
                            listContent.Add(laydanhsachcaccot[j].PhanTu[i].TenDoiTuong);
                        }
                        listResult.Add(listContent);
                    }

                    List<string> listNoiDung = new List<string>();
                    listNoiDung.Add(title);

                    foreach (List<string> ItemArr in listResult)
                    {
                        string strTemp = string.Empty;
                        for (int irun=0 ;irun< ItemArr.Count;irun++)
                        {
                            if (irun == 0)
                                strTemp += ItemArr[irun];
                            else
                                strTemp += "," + ItemArr[irun];
                        }
                        listNoiDung.Add(strTemp);
                    }
                    GhiFileCSV(listNoiDung);

                }
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            List<double> kiemtra = new List<double> { 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9 };
            var result = from id in kiemtra
                         group id by id into g
                         orderby g.Count() descending
                         select new { Id = g.Key, Count = g.Count() };
            foreach (var x in result)
            {
                double a = x.Id; //số 
                int b = x.Count; //số lần xuất hiện.
            }
        }
    }
}
